package com.guli.gulimall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.guli.common.utils.R;
import com.guli.gulimall.product.config.GuliESConfig;
import com.guli.gulimall.product.dao.*;
import com.guli.gulimall.product.entity.*;
import com.guli.gulimall.product.feign.ConponFeignService;
import com.guli.gulimall.product.service.*;
import com.guli.gulimall.product.to.MemberPriceTo;
import com.guli.gulimall.product.to.SkuFullReductionTo;
import com.guli.gulimall.product.to.SkuLadderTo;
import com.guli.gulimall.product.to.SpuBoundsTo;
import com.guli.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;


@SuppressWarnings("all")
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ConponFeignService conponFeignService;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public R addSpu(SpuVo spuVo) {
//1
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
//2
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        String url="";
        List<String> decript = spuVo.getDecript();
        if (!decript.isEmpty()){
            for (String s : decript) {
                url+=","+s;
            }
            url = url.substring(1);
            spuInfoDescEntity.setDecript(url);
            spuInfoDescDao.insert(spuInfoDescEntity);
        }
// 3
        List<String> images = spuVo.getImages();
        if (!images.isEmpty()){
            List<SpuImagesEntity> collect = images.stream().map(img -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(img);
                spuImagesEntity.setImgSort(0);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(collect);
        }
// 4
        List<BaseAttrs> baseAttrs = spuVo.getBaseAttrs();
        if (!baseAttrs.isEmpty()){
            List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                productAttrValueEntity.setAttrId(attr.getAttrId());
                productAttrValueEntity.setAttrValue(attr.getAttrValues());
                productAttrValueEntity.setQuickShow(attr.getShowDesc());

                AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
                productAttrValueEntity.setSearchType(attrEntity.getSearchType());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(collect);
        }
// 5 TODO
        Bounds bounds = spuVo.getBounds();
        if (bounds != null){
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            spuBoundsTo.setBuyBounds(bounds.getBuyBounds());
            spuBoundsTo.setGrowBounds(bounds.getGrowBounds());
            spuBoundsTo.setSpuId(spuInfoEntity.getId());
           R r1 =  conponFeignService.saveSpuBounds(spuBoundsTo);
        }

        List<Skus> skus = spuVo.getSkus();
        if (!skus.isEmpty()){
            for (Skus sku : skus) {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());

                List<Images> images1 = sku.getImages();
                if (!images1.isEmpty()){
                    Images images2 = images1.stream().filter(img -> {
                        return img.getDefaultImg().equals(1);
                    }).findFirst().get();
                    skuInfoEntity.setSkuDefaultImg(images2.getImgUrl());
                }
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setPrice(sku.getPrice());
                skuInfoEntity.setSkuSubtitle(sku.getSkuSubtitle());
                skuInfoEntity.setSkuTitle(sku.getSkuTitle());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSkuDesc(spuInfoEntity.getSpuDescription());
                skuInfoEntity.setSkuName(sku.getSkuName());
                skuInfoDao.insert(skuInfoEntity);

                List<Images> images2 = sku.getImages();
                if (!images2.isEmpty()){
                    List<SkuImagesEntity> collect = images2.stream().filter(img -> {
                        return StringUtils.isNotEmpty(img.getImgUrl());
                    }).map(image -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuImagesEntity.setDefaultImg(image.getDefaultImg());
                        skuImagesEntity.setImgUrl(image.getImgUrl());
                        skuImagesEntity.setImgSort(0);
                        return skuImagesEntity;
                    }).collect(Collectors.toList());
                    skuImagesService.saveBatch(collect);
                }

                List<Attr> attrs = sku.getAttr();
                if (!attrs.isEmpty()){
                    List<SkuSaleAttrValueEntity> collect = attrs.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                        skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                        skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());

                        AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
                        skuSaleAttrValueEntity.setSearchType(attrEntity.getSearchType());
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(collect);
                }
                SkuLadderTo skuLadderTo = new SkuLadderTo();
                skuLadderTo.setAddOther(sku.getCountStatus());
                skuLadderTo.setFullCount(sku.getFullCount());
                skuLadderTo.setDiscount(sku.getDiscount());
                skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
                R r2 = conponFeignService.saveSkuLadder(skuLadderTo);

//                10
                SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
                skuFullReductionTo.setAddOther(sku.getPriceStatus());
                skuFullReductionTo.setReducePrice(sku.getReducePrice());
                skuFullReductionTo.setFullPrice(sku.getFullPrice());
                skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());

               R r3 = conponFeignService.saveSkuFullReductionTo(skuFullReductionTo);

                List<MemberPrice> memberPrices = sku.getMemberPrice();
                if (!memberPrices.isEmpty()){
                    List<MemberPriceTo> collect = memberPrices.stream().map(m -> {
                        MemberPriceTo memberPriceTo = new MemberPriceTo();
                        memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                        memberPriceTo.setMemberPrice(m.getPrice());
                        memberPriceTo.setMemberLevelName(m.getName());
                        memberPriceTo.setMemberLevelId(m.getId());
                        return memberPriceTo;
                    }).collect(Collectors.toList());
                    R r4 =conponFeignService.saveMemberPriceTo(collect);
                }
            }

        }
        return null;
    }

    @Override
    public void up(Long spuId) {
        try {
            //1.根据spu查询当前商品的基本信息
            SpuInfoEntity spuInfoEntity = baseMapper.selectById(spuId);
            //2.根据spuId查询商品需要检索的规格参数
            QueryWrapper<ProductAttrValueEntity> w1 = new QueryWrapper<>();
            w1.eq("search_type", 1);
            w1.eq("spu_id", spuId);
            List<ProductAttrValueEntity> list = productAttrValueService.list(w1);
            List<SkuEsVo.Attr> collect = null;
            if (list != null) {
                collect = list.stream().map(attr -> {
                    SkuEsVo.Attr attrVo = new SkuEsVo.Attr();
                    attrVo.setAttrId(attr.getAttrId());
                    attrVo.setAttrName(attr.getAttrName());
                    attrVo.setAttrValue(attr.getAttrValue());
                    return attrVo;
                }).collect(Collectors.toList());
            }
            //3.根据spuId查询对应的sku集合
            QueryWrapper<SkuInfoEntity> w2 = new QueryWrapper<>();
            w2.eq("spu_id", spuId);
            List<SkuInfoEntity> skuList = skuInfoDao.selectList(w2);

            BulkRequest bulkRequest = new BulkRequest("product");

            for (SkuInfoEntity sku : skuList) {
                IndexRequest indexRequest = new IndexRequest();

                //5. 把每个查询到的sku信息保存到esVo对象中
                SkuEsVo skuEsVo = new SkuEsVo();
                skuEsVo.setCatalogId(spuInfoEntity.getCatalogId());
                CategoryEntity categoryEntity = categoryDao.selectById(spuInfoEntity.getCatalogId());
                skuEsVo.setCatelogName(categoryEntity.getName());
                skuEsVo.setBrandId(spuInfoEntity.getBrandId());
                BrandEntity brandEntity = brandDao.selectById(spuInfoEntity.getBrandId());
                skuEsVo.setBrandName(brandEntity.getName());
                skuEsVo.setBrandImg(brandEntity.getLogo());
                skuEsVo.setHotScore(5L);
                //TODO feign调用查询仓储服务
                skuEsVo.setHasStock(true);
                skuEsVo.setSaleCount(sku.getSaleCount());
                skuEsVo.setSkuImg(sku.getSkuDefaultImg());
                skuEsVo.setSkuPrice(sku.getPrice());
                skuEsVo.setSkuTitle(sku.getSkuTitle());
                skuEsVo.setSkuId(sku.getSkuId());
                skuEsVo.setSpuId(sku.getSpuId());
                //4. 遍历每个sku 查询每个sku需要检索的销售属性
                QueryWrapper<SkuSaleAttrValueEntity> w3 = new QueryWrapper<>();
                w3.eq("search_type", 1);
                w3.eq("sku_id", sku.getSkuId());
                List<SkuSaleAttrValueEntity> list1 = skuSaleAttrValueService.list(w3);
                if (list1 != null) {
                    List<SkuEsVo.Attr> list2 = list1.stream().map(attr -> {
                        SkuEsVo.Attr attrVo = new SkuEsVo.Attr();
                        attrVo.setAttrId(attr.getAttrId());
                        attrVo.setAttrName(attr.getAttrName());
                        attrVo.setAttrValue(attr.getAttrValue());
                        return attrVo;
                    }).collect(Collectors.toList());
                    //合并集合
                    list2.addAll(collect);
                    skuEsVo.setAttrs(list2);
                }
                //封装es对象
                indexRequest.id(sku.getSkuId().toString());
                String jsonString = JSONObject.toJSONString(skuEsVo);

                indexRequest.source(jsonString, XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            //6. 同步es
            if (list.size()>0){
                client.bulk(bulkRequest,GuliESConfig.COMMON_OPTIONS);
            }
            //7. 修改商品的状态 变成已上架
            spuInfoEntity.setUpdateTime(new Date());
            spuInfoEntity.setPublishStatus(1);
            baseMapper.updateById(spuInfoEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

}